<?php
/**
 * @version		$Id: gencs.php $
 * @copyright	Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
 * @license		GNU General Public License version 2 or later; see LICENSE.txt
 */

// No direct access.
defined('_JEXEC') or die;

jimport('joomla.application.component.controlleradmin');

/**
 * Gen Code controller class.
 *
 * @package		Joomla.Administrator
 * @subpackage	com_gencode
 * @since		1.6
 */
class GenCodeControllerGenCs extends JControllerAdmin
{
	/**
	 * @var		string	The prefix to use with controller messages.
	 * @since	1.6
	 */
	protected $text_prefix = 'COM_GENCODE_GENCS';

	/**
	 * Proxy for getModel.
	 * @since	1.6
	 */
	public function getModel($name = 'GenC', $prefix = 'GenCodeModel', $config = array('ignore_request' => true))
	{
		$model = parent::getModel($name, $prefix, $config);
		return $model;
	}
	
	public function gencode()
	{
		$componentId = JRequest::getVar('component_id');
		
		require_once JPATH_COMPONENT_ADMINISTRATOR . DS . 'helpers' . DS . 'genarate.helper.class.php';
		$helper = new GenerateHelper($componentId);
		$component = $helper->buildFiles();
		
		$path = JPATH_ROOT . DS . 'tmp' . DS . 'com_gencode' . DS . 'com_'.$component;
		
		$fullPath = $path.'.zip';
		
		//download file
		if ($fd = fopen ($fullPath, "r"))
		{
			$fsize = filesize($fullPath);
			$path_parts = pathinfo($fullPath);
			$ext = strtolower($path_parts["extension"]);
			
			header("Content-type: application/octet-stream");
			header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
			
			header("Content-length: $fsize");
			header("Cache-control: private"); //use this to open files directly
			
			while(!feof($fd)) 
			{
				$buffer = fread($fd, 2048);
				echo $buffer;
			}
		}
		
		fclose ($fd);
		
		//delete files
		@unlink($fullPath);
		
		//delete folder
		$this->rrmdir($path);
		
		exit;
	}
	
	/*
	 * Function to recursively delete a directory that is not empty
	*/
	function rrmdir($dir)
	{
		if (is_dir($dir))
		{
			$objects = scandir($dir);
	
			foreach ($objects as $object)
			{
				if ($object != "." && $object != "..")
				{
					if (filetype($dir."/".$object) == "dir")
						self::rrmdir($dir."/".$object);
					else
						@unlink($dir."/".$object);
				}
			}
	
			reset($objects);
	
			@rmdir($dir);
		}
	}
}